import pygame
import sys
import math

# 初始化pygame
pygame.init()
pygame.font.init()

# 确保中文能正常显示
font = pygame.font.SysFont(['SimHei', 'WenQuanYi Micro Hei', 'Heiti TC'], 36)
small_font = pygame.font.SysFont(['SimHei', 'WenQuanYi Micro Hei', 'Heiti TC'], 24)

# 游戏窗口设置
WIDTH, HEIGHT = 700, 750
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("跳棋")

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BOARD_COLOR = (240, 217, 181)  # 棋盘颜色（米色）
GRID_COLOR = (139, 69, 19)  # 网格颜色（棕色）
HIGHLIGHT_COLOR = (255, 215, 0)  # 高亮颜色（金色）
SELECTED_COLOR = (0, 255, 0)  # 选中颜色（绿色）

# 棋盘设置
BOARD_SIZE = 8  # 8x8的棋盘
GRID_SIZE = 70  # 网格大小
BOARD_MARGIN = (WIDTH - BOARD_SIZE * GRID_SIZE) // 2  # 棋盘边距

# 棋子类型
RED_PAWN = 1
RED_KING = 2
BLUE_PAWN = 3
BLUE_KING = 4

# 游戏状态
game_board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = RED_PAWN  # 红方先行
selected_piece = None  # 当前选中的棋子
game_over = False
winner = None


# 初始化棋盘
def init_board():
    # 放置红方棋子
    for i in range(3):
        for j in range(BOARD_SIZE):
            if (i + j) % 2 == 1:  # 只在深色格子上放置棋子
                game_board[i][j] = RED_PAWN

    # 放置蓝方棋子
    for i in range(BOARD_SIZE - 3, BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if (i + j) % 2 == 1:  # 只在深色格子上放置棋子
                game_board[i][j] = BLUE_PAWN


# 绘制棋盘
def draw_board():
    # 绘制背景
    screen.fill(BOARD_COLOR)

    # 绘制网格
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if (i + j) % 2 == 1:  # 深色格子
                pygame.draw.rect(screen, GRID_COLOR,
                                 (BOARD_MARGIN + j * GRID_SIZE, BOARD_MARGIN + i * GRID_SIZE,
                                  GRID_SIZE, GRID_SIZE))


# 绘制棋子
def draw_pieces():
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            piece = game_board[i][j]
            if piece != 0:
                # 绘制棋子
                color = RED if piece in [RED_PAWN, RED_KING] else BLUE
                pygame.draw.circle(screen, color,
                                   (BOARD_MARGIN + j * GRID_SIZE + GRID_SIZE // 2,
                                    BOARD_MARGIN + i * GRID_SIZE + GRID_SIZE // 2),
                                   GRID_SIZE // 2 - 5)

                # 绘制棋子边框
                pygame.draw.circle(screen, BLACK,
                                   (BOARD_MARGIN + j * GRID_SIZE + GRID_SIZE // 2,
                                    BOARD_MARGIN + i * GRID_SIZE + GRID_SIZE // 2),
                                   GRID_SIZE // 2 - 5, 2)

                # 如果是国王（将），在棋子上画一个小圆圈
                if piece in [RED_KING, BLUE_KING]:
                    pygame.draw.circle(screen, WHITE if color == RED else YELLOW,
                                       (BOARD_MARGIN + j * GRID_SIZE + GRID_SIZE // 2,
                                        BOARD_MARGIN + i * GRID_SIZE + GRID_SIZE // 2),
                                       GRID_SIZE // 4, 2)

    # 高亮显示选中的棋子
    if selected_piece is not None:
        row, col = selected_piece
        pygame.draw.circle(screen, SELECTED_COLOR,
                           (BOARD_MARGIN + col * GRID_SIZE + GRID_SIZE // 2,
                            BOARD_MARGIN + row * GRID_SIZE + GRID_SIZE // 2),
                           GRID_SIZE // 2 - 2, 3)


# 获取可以移动到的位置
def get_valid_moves(row, col):
    moves = []
    piece = game_board[row][col]

    if piece == 0:
        return moves

    is_red = piece in [RED_PAWN, RED_KING]
    is_king = piece in [RED_KING, BLUE_KING]

    # 方向：红方向下移动，蓝方向上移动，国王可以双向移动
    directions = []
    if is_red:
        directions.append((1, -1))  # 右下
        directions.append((1, 1))  # 左下
        if is_king:
            directions.append((-1, -1))  # 右上
            directions.append((-1, 1))  # 左上
    else:
        directions.append((-1, -1))  # 右上
        directions.append((-1, 1))  # 左上
        if is_king:
            directions.append((1, -1))  # 右下
            directions.append((1, 1))  # 左下

    # 检查普通移动
    for dr, dc in directions:
        new_row = row + dr
        new_col = col + dc

        if 0 <= new_row < BOARD_SIZE and 0 <= new_col < BOARD_SIZE:
            if game_board[new_row][new_col] == 0:
                moves.append((new_row, new_col))

    # 检查跳吃移动
    for dr, dc in directions:
        new_row = row + 2 * dr
        new_col = col + 2 * dc

        if 0 <= new_row < BOARD_SIZE and 0 <= new_col < BOARD_SIZE:
            if game_board[new_row][new_col] == 0:
                mid_row = row + dr
                mid_col = col + dc
                if game_board[mid_row][mid_col] != 0:
                    if (is_red and game_board[mid_row][mid_col] in [BLUE_PAWN, BLUE_KING]) or \
                            (not is_red and game_board[mid_row][mid_col] in [RED_PAWN, RED_KING]):
                        moves.append((new_row, new_col))

    return moves


# 检查是否有跳吃的机会
def has_jump_move(player):
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if (player == RED_PAWN and game_board[i][j] in [RED_PAWN, RED_KING]) or \
                    (player == BLUE_PAWN and game_board[i][j] in [BLUE_PAWN, BLUE_KING]):
                moves = get_valid_moves(i, j)
                for move in moves:
                    if abs(move[0] - i) == 2:  # 跳吃移动
                        return True
    return False


# 移动棋子
def move_piece(from_row, from_col, to_row, to_col):
    global current_player, selected_piece

    piece = game_board[from_row][from_col]
    if piece == 0:
        return False

    moves = get_valid_moves(from_row, from_col)
    if (to_row, to_col) not in moves:
        return False

    # 移动棋子
    game_board[to_row][to_col] = piece
    game_board[from_row][from_col] = 0

    # 检查是否有跳吃
    if abs(to_row - from_row) == 2:
        # 计算被吃掉的棋子位置
        mid_row = (from_row + to_row) // 2
        mid_col = (from_col + to_col) // 2
        game_board[mid_row][mid_col] = 0

    # 检查是否可以升级为国王
    if piece == RED_PAWN and to_row == BOARD_SIZE - 1:
        game_board[to_row][to_col] = RED_KING
    elif piece == BLUE_PAWN and to_row == 0:
        game_board[to_row][to_col] = BLUE_KING

    # 检查是否还有跳吃机会
    if abs(to_row - from_row) == 2:
        # 如果是跳吃，检查是否还有连续跳吃
        continue_jumps = get_valid_moves(to_row, to_col)
        can_continue = False
        for jump in continue_jumps:
            if abs(jump[0] - to_row) == 2:
                can_continue = True
                break

        if can_continue:
            selected_piece = (to_row, to_col)
            return True

    # 切换玩家
    current_player = BLUE_PAWN if current_player == RED_PAWN else RED_PAWN
    selected_piece = None
    return True


# 检查游戏是否结束
def check_game_over():
    red_pieces = 0
    blue_pieces = 0

    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if game_board[i][j] in [RED_PAWN, RED_KING]:
                red_pieces += 1
            elif game_board[i][j] in [BLUE_PAWN, BLUE_KING]:
                blue_pieces += 1

    # 如果一方没有棋子了，另一方获胜
    if red_pieces == 0:
        return True, BLUE_PAWN
    if blue_pieces == 0:
        return True, RED_PAWN

    # 检查当前玩家是否还有可移动的棋子
    current_has_moves = False
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if (current_player == RED_PAWN and game_board[i][j] in [RED_PAWN, RED_KING]) or \
                    (current_player == BLUE_PAWN and game_board[i][j] in [BLUE_PAWN, BLUE_KING]):
                if get_valid_moves(i, j):
                    current_has_moves = True
                    break
        if current_has_moves:
            break

    if not current_has_moves:
        # 当前玩家没有可移动的棋子，另一方获胜
        winner = BLUE_PAWN if current_player == RED_PAWN else RED_PAWN
        return True, winner

    return False, None


# 重置游戏
def reset_game():
    global game_board, current_player, selected_piece, game_over, winner
    game_board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
    current_player = RED_PAWN
    selected_piece = None
    game_over = False
    winner = None
    init_board()


# 初始化棋盘
init_board()

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # 左键点击
            if not game_over:
                x, y = event.pos
                # 计算点击的棋盘位置
                col = (x - BOARD_MARGIN) // GRID_SIZE
                row = (y - BOARD_MARGIN) // GRID_SIZE

                if 0 <= row < BOARD_SIZE and 0 <= col < BOARD_SIZE:
                    # 如果点击了自己的棋子，选中它
                    if game_board[row][col] != 0 and \
                            ((current_player == RED_PAWN and game_board[row][col] in [RED_PAWN, RED_KING]) or \
                             (current_player == BLUE_PAWN and game_board[row][col] in [BLUE_PAWN, BLUE_KING])):
                        selected_piece = (row, col)
                    # 如果已经选中了棋子，尝试移动
                    elif selected_piece is not None:
                        from_row, from_col = selected_piece
                        move_piece(from_row, from_col, row, col)

                        # 检查游戏是否结束
                        game_over, winner = check_game_over()
            else:
                # 游戏结束后点击重置游戏
                reset_game()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_r:  # 按R键重置游戏
                reset_game()

    # 绘制游戏
    draw_board()
    draw_pieces()

    # 显示当前玩家
    player_text = f"当前玩家: {'红方' if current_player == RED_PAWN else '蓝方'}"
    text_surface = small_font.render(player_text, True, BLACK)
    screen.blit(text_surface, (WIDTH // 2 - text_surface.get_width() // 2, HEIGHT - 60))

    # 显示游戏结束信息
    if game_over:
        winner_text = f"游戏结束! {'红方' if winner == RED_PAWN else '蓝方'}获胜!"
        text_surface = font.render(winner_text, True, BLACK)
        screen.blit(text_surface, (WIDTH // 2 - text_surface.get_width() // 2, HEIGHT - 100))

        restart_text = "点击任意位置或按R键重新开始"
        text_surface = small_font.render(restart_text, True, BLACK)
        screen.blit(text_surface, (WIDTH // 2 - text_surface.get_width() // 2, HEIGHT - 60))

    # 更新显示
    pygame.display.flip()

pygame.quit()
sys.exit()